// 欢迎
package hello

import (
	"fmt"
	"math"
	"math/cmplx"
	"math/rand"
	"runtime"
	"time"
)

func myadd(x int, y int) int {
	return x + y
}

//同类型变量定义
func myadd2(x, y int) int {
	return x + y
}

//返回多值
func swap(x, y string) (string, string) {
	return y, x
}

//命名返回值
func split(sum int) (x, y int) {
	x = sum * 4 / 9
	y = sum - x
	return
}

//变量
var (
	ToBe   bool       = false
	MaxInt uint64     = 1<<64 - 1
	z      complex128 = cmplx.Sqrt(-5 + 12i)
)

func test_simple() {
	fmt.Println("你好,新朋友!")
	fmt.Println("现在是", time.Now())
	fmt.Println("我喜欢的数字是", rand.Intn(10))
	fmt.Printf("现在你有%.0g个错误.\n", math.Nextafter(2, 3))
	fmt.Println(math.Pi)
	fmt.Println(myadd(42, 13))
	fmt.Println(myadd2(42, 13))
	a, b := swap("你好", "世界")
	a, b = b, a
	a, b = b, a
	fmt.Println(a, b)
	fmt.Println(split(17))

	const f = "%T(%v)\n"
	fmt.Printf(f, ToBe, ToBe)
	fmt.Printf(f, MaxInt, MaxInt)
	fmt.Printf(f, z, z)
}

func Main1() {
	test_simple()
	print_zero()
	type_convertion()
	test_for()
	test_if()
	loop_sample()
	test_switch()
	test_switch2()
	test_switch3_no_condition()
	test_defer()
	test_defer_stack()
}

func test_defer() {
	defer fmt.Println("朋友!")
	fmt.Print("你好,")
}

func test_defer_stack() {
	fmt.Println("计数")
	for i := 0; i < 10; i++ {
		defer fmt.Println(i)
	}
	fmt.Println("完成")
}

func print_zero() {
	var i int
	var f float64
	var b bool
	var s string
	fmt.Printf("%v %v %v %q\n", i, f, b, s)
}

func type_convertion() {
	x, y := 3, 4
	f := math.Sqrt(float64(x*x + y*y))
	z := int(f)
	fmt.Println(x, y, z)
}

func test_for() {
	sum := 0
	for i := 0; i < 10; i++ {
		sum += i
	}
	fmt.Println(sum)

	sum = 1
	for sum < 1000 {
		sum += sum
	}
	fmt.Println(sum)
}

func mysqrt(x float64) string {
	if x < 0 {
		return mysqrt(-x) + "i"
	}
	return fmt.Sprint(math.Sqrt(x))
}

func pow(x, n, lim float64) float64 {
	if v := math.Pow(x, n); v < lim {
		return v
	} else {
		fmt.Printf("%g >= %g\n", v, lim)
	}
	return lim
}

func newton_sqrt(x float64) float64 {
	z := 1.0
	zp := z
	i := 0
	for {
		i++
		zp = z
		z -= (z*z - x) / (2 * z)
		if math.Abs(z-zp) < 0.0001 {
			fmt.Println(i, z, zp)
			break
		}
	}
	return z
}

func test_if() {
	fmt.Println(mysqrt(2), mysqrt(-4))
	fmt.Println(pow(3, 2, 10), pow(3, 3, 20))
}

func loop_sample() {
	v := 1000.0
	fmt.Println("\n\n")
	fmt.Println(newton_sqrt(v), math.Sqrt(v))
}

func test_switch() {
	fmt.Print("Go运行在")
	switch os := runtime.GOOS; os {
	case "darwin":
		fmt.Println("OS X.")
	case "linux":
		fmt.Println("Linux.")
	default:
		fmt.Printf("%s.\n", os)
	}
}

func test_switch2() {
	fmt.Println("星期六是什么时候?")
	today := time.Now().Weekday()
	switch time.Saturday {
	case today + 0:
		fmt.Println("是今天.")
	case today + 1:
		fmt.Println("是明天.")
	case today + 2:
		fmt.Println("是后天.")
	default:
		fmt.Println("还早.")
	}
}

func test_switch3_no_condition() {
	t := time.Now()
	switch {
	case t.Hour() < 12:
		fmt.Println("早上好!")
	case t.Hour() < 17:
		fmt.Println("下午好!")
	default:
		fmt.Println("晚上好!")
	}
}
